package com.yuyang.wifi.activitys.mine;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;

import com.yuyang.wifi.R;
import com.yuyang.wifi.SplashActivity;
import com.yuyang.wifi.base.BaseActivity;
import com.yuyang.wifi.base.BaseResult;
import com.yuyang.wifi.constant.AppConstant;
import com.yuyang.wifi.service.LiveWallpaperService;
import com.yuyang.wifi.utils.GetIPAdsUtil;
import com.yuyang.wifi.utils.GetMacAdsUtil;
import com.yuyang.wifi.utils.RxUtil;
import com.yuyang.wifi.utils.Skip;
import com.yuyang.wifi.utils.SpUtil;
import com.yuyang.wifi.utils.network.BaseDataSubscriber;
import com.yuyang.wifi.utils.network.HttpErrorHandler;
import com.yuyang.wifi.utils.network.HttpManager;
import com.yuyang.wifi.utils.network.RxDataInstance;
import com.yuyang.wifi.views.MittUtils;
import com.yuyang.wifi.views.NormalWhiteTopBar;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import butterknife.BindView;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * created by mej
 * on 2021/8/14
 */
public class HintClickActivity extends BaseActivity {

    @BindView(R.id.tool_bar)
    NormalWhiteTopBar toolBar;

    private final static int REQUEST_CODE_SET_WALLPAPER = 0x001;
    private String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int REQUEST_PERMISSIONS = 1;
    private String mJumpType;
    private String mOaid;

    @Override
    protected void initActionBar() {
        toolBar.setActionBarCentreTitle("");
        toolBar.setsetActionBarBottomLine(false);
        toolBar.setsetActionBarLeftIcon(R.mipmap.toolbar_left_arrow_back_icon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_hint;
    }

    @Override
    protected void initContentView() {


        if (null != getIntent()) {
            mJumpType = getIntent().getStringExtra("mJumpType");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            boolean isAllGranted = checkPermissionAllGranted(permissions);
            if (!isAllGranted) {
                ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSIONS);
            }
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setLiveWallpaper(HintClickActivity.this, HintClickActivity.REQUEST_CODE_SET_WALLPAPER);
            }
        }, 1800);
    }

    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mOaid = SpUtil.find(AppConstant.KEY_OAID);
        if (TextUtils.isEmpty(mOaid)) {
            new MittUtils().getDeviceIds(this, new MittUtils.AppIdsUpdater() {
                @Override
                public void OnIdsAvailed(boolean isSupport, String oaid) {
                    SpUtil.saveOrUpdate(AppConstant.KEY_OAID, oaid);
                    Log.e("参数", "oaid:=== " + oaid);
                }
            });
        }

        boolean pagerServiceRunning = isPagerServiceRunning();
        if (pagerServiceRunning) {
            wallpaper();
            finish();
        }
    }

    /**
     * 跳转到系统设置壁纸界面
     *
     * @param paramActivity
     */
    public void setLiveWallpaper(Activity paramActivity, int requestCode) {

        try {
            Intent localIntent = new Intent();
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {//ICE_CREAM_SANDWICH_MR1  15
//                localIntent.setAction(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);//android.service.wallpaper.CHANGE_LIVE_WALLPAPER
//                //android.service.wallpaper.extra.LIVE_WALLPAPER_COMPONENT
//                localIntent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT
//                        , new ComponentName(this
//                                , LiveWallpaperService.class.getCanonicalName()));
                Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
                intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
                        new ComponentName(this, LiveWallpaperService.class));
                startActivity(intent);
            } else {
                localIntent.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);//android.service.wallpaper.LIVE_WALLPAPER_CHOOSER
            }
            paramActivity.startActivityForResult(localIntent, requestCode);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    private boolean isPagerServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("com.yuyang.wifi.service.LiveWallpaperService".equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    private void wallpaper() {
        String mac = GetMacAdsUtil.getMac(HintClickActivity.this);
        String ipAddress = GetIPAdsUtil.getIPAddress(HintClickActivity.this);
        String androidid = getAndroidId(HintClickActivity.this);
        String imei = getDeviceIds(HintClickActivity.this);
        RxDataInstance.getInstance().initMap(HintClickActivity.this)
                .put("imei", imei)
                .put("oaid", mOaid)
                .put("idfa", "")
                .put("androidid", androidid)
                .put("mac", mac)
                .put("ip", ipAddress);
        HttpManager.getInstance().getApi().wallpaper(RxDataInstance.getInstance().getParamMap())
                .compose(RxUtil.<BaseResult>bindLifecycleAndApplySchedulers(this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseDataSubscriber<BaseResult>(new HttpErrorHandler() {
                    @Override
                    public void onHttpError(BaseResult result) {

                    }

                    @Override
                    public void onHttpException(Throwable e) {
                        // dismissLoadingDialog();
                    }
                }) {
                    @Override
                    public void onDataNext(BaseResult result) {
                        int resultCode = result.getResultCode();

                    }
                });

    }


    private static String getAndroidId(Context context) {
        String deviceID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        if (!TextUtils.isEmpty(deviceID)) {
            return deviceID;
        }
        return deviceID;
    }

    //获取设备ID
    public static String getDeviceIds(Context context) {

        try {
            TelephonyManager telephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (telephonyMgr != null) {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    return "";
                }
                String deviceId = telephonyMgr.getDeviceId();
                //Log.e("channel", "onViewClicked:" + deviceId);
                return deviceId;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return "";
    }
}
